package com.kongjs.application.service.impl;

import com.kongjs.application.cache.UserCacheManager;
import com.kongjs.application.model.dto.UserDetailsDTO;
import com.kongjs.application.model.entity.Users;
import com.kongjs.application.service.IUsersService;
import jakarta.annotation.Resource;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.Optional;
import java.util.Set;

@Service
public class UserDetailsServiceImpl implements UserDetailsService {
    @Resource
    private IUsersService usersService;
    @Resource
    private UserCacheManager userCacheManager;

    @Override
    public UserDetailsDTO loadUserByUsername(String username) throws UsernameNotFoundException {
        UserDetailsDTO dto = new UserDetailsDTO();
        try {
            if (userCacheManager.notExistsUser(username)) {
                throw new UsernameNotFoundException(username);
            }
            Optional<Users> optionalUsers = usersService.lambdaQuery().eq(Users::getUsername, username).oneOpt();
            if (optionalUsers.isEmpty()) {
                throw new UsernameNotFoundException(username);
            }
            Users users = optionalUsers.get();
            dto.setTenantId(String.valueOf(users.getTenantId()));
            dto.setUserId(String.valueOf(users.getId()));
            dto.setUsername(users.getUsername());
            dto.setPassword(users.getPassword());
            dto.setEnabled(users.getEnabled() != null && users.getEnabled() == 1);
            dto.setAuthorities(Set.of());
        } catch (UsernameNotFoundException e) {
            throw e;
        } catch (Exception e) {
            throw new UsernameNotFoundException(username);
        }
        return dto;
    }
}
